import React, { useState } from 'react';

const DataManager: React.FC = () => {
  const [isExporting, setIsExporting] = useState(false);
  const [isImporting, setIsImporting] = useState(false);
  const [importFile, setImportFile] = useState<File | null>(null);

  const handleExport = async (type: 'all' | 'articles' | 'settings') => {
    setIsExporting(true);
    
    try {
      // Simulate export process
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      const data = {
        all: {
          articles: [
            { id: '1', title: 'Sample Article', content: 'Content...', date: '2024-01-01' }
          ],
          settings: { theme: 'system', language: 'en' },
          profile: { name: 'John Doe', email: 'john@example.com' }
        },
        articles: [
          { id: '1', title: 'Sample Article', content: 'Content...', date: '2024-01-01' }
        ],
        settings: { theme: 'system', language: 'en' }
      };

      const exportData = type === 'all' ? data.all : data[type];
      const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      
      const a = document.createElement('a');
      a.href = url;
      a.download = `apple-blog-${type}-${new Date().toISOString().split('T')[0]}.json`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
      
    } catch (error) {
      console.error('Export failed:', error);
    } finally {
      setIsExporting(false);
    }
  };

  const handleImport = async () => {
    if (!importFile) return;
    
    setIsImporting(true);
    
    try {
      const text = await importFile.text();
      const data = JSON.parse(text);
      
      // Simulate import process
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      console.log('Imported data:', data);
      alert('Data imported successfully!');
      setImportFile(null);
      
    } catch (error) {
      console.error('Import failed:', error);
      alert('Import failed. Please check your file format.');
    } finally {
      setIsImporting(false);
    }
  };

  const handleClearData = async (type: 'articles' | 'settings' | 'all') => {
    const confirmMessage = {
      articles: 'This will delete all your articles. This action cannot be undone.',
      settings: 'This will reset all your settings to default values.',
      all: 'This will delete ALL your data including articles, settings, and profile. This action cannot be undone.'
    };

    if (!window.confirm(`Are you sure? ${confirmMessage[type]}`)) {
      return;
    }

    try {
      // Simulate data clearing
      await new Promise(resolve => setTimeout(resolve, 1000));
      alert(`${type === 'all' ? 'All data' : type.charAt(0).toUpperCase() + type.slice(1)} cleared successfully!`);
    } catch (error) {
      console.error('Clear data failed:', error);
      alert('Failed to clear data. Please try again.');
    }
  };

  return (
    <div className="space-y-8">
      <div>
        <h2 className="text-xl font-semibold text-ios-gray-900 dark:text-white mb-4">
          Data Management
        </h2>
        <p className="text-ios-gray-600 dark:text-ios-gray-400 mb-6">
          Export, import, or manage your blog data
        </p>
      </div>

      {/* Export Section */}
      <div className="space-y-4">
        <h3 className="text-lg font-medium text-ios-gray-900 dark:text-white">
          Export Data
        </h3>
        <p className="text-sm text-ios-gray-600 dark:text-ios-gray-400">
          Download your data in JSON format for backup or migration
        </p>
        
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div className="p-4 bg-ios-gray-50 dark:bg-ios-gray-700 rounded-apple-lg">
            <div className="flex items-center space-x-3 mb-3">
              <div className="w-10 h-10 bg-ios-blue/10 rounded-apple-md flex items-center justify-center">
                <svg className="w-5 h-5 text-ios-blue" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                </svg>
              </div>
              <div>
                <h4 className="font-medium text-ios-gray-900 dark:text-white">Articles</h4>
                <p className="text-xs text-ios-gray-500 dark:text-ios-gray-400">Export all articles</p>
              </div>
            </div>
            <button
              onClick={() => handleExport('articles')}
              disabled={isExporting}
              className="w-full px-3 py-2 bg-white dark:bg-ios-gray-600 hover:bg-ios-gray-50 dark:hover:bg-ios-gray-500 text-ios-gray-700 dark:text-ios-gray-200 rounded-apple-md border border-ios-gray-200 dark:border-ios-gray-500 transition-colors disabled:opacity-50"
            >
              Export Articles
            </button>
          </div>

          <div className="p-4 bg-ios-gray-50 dark:bg-ios-gray-700 rounded-apple-lg">
            <div className="flex items-center space-x-3 mb-3">
              <div className="w-10 h-10 bg-ios-green/10 rounded-apple-md flex items-center justify-center">
                <svg className="w-5 h-5 text-ios-green" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                </svg>
              </div>
              <div>
                <h4 className="font-medium text-ios-gray-900 dark:text-white">Settings</h4>
                <p className="text-xs text-ios-gray-500 dark:text-ios-gray-400">Export preferences</p>
              </div>
            </div>
            <button
              onClick={() => handleExport('settings')}
              disabled={isExporting}
              className="w-full px-3 py-2 bg-white dark:bg-ios-gray-600 hover:bg-ios-gray-50 dark:hover:bg-ios-gray-500 text-ios-gray-700 dark:text-ios-gray-200 rounded-apple-md border border-ios-gray-200 dark:border-ios-gray-500 transition-colors disabled:opacity-50"
            >
              Export Settings
            </button>
          </div>

          <div className="p-4 bg-ios-gray-50 dark:bg-ios-gray-700 rounded-apple-lg">
            <div className="flex items-center space-x-3 mb-3">
              <div className="w-10 h-10 bg-ios-orange/10 rounded-apple-md flex items-center justify-center">
                <svg className="w-5 h-5 text-ios-orange" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                </svg>
              </div>
              <div>
                <h4 className="font-medium text-ios-gray-900 dark:text-white">Everything</h4>
                <p className="text-xs text-ios-gray-500 dark:text-ios-gray-400">Complete backup</p>
              </div>
            </div>
            <button
              onClick={() => handleExport('all')}
              disabled={isExporting}
              className="w-full px-3 py-2 bg-ios-orange text-white hover:bg-ios-orange/90 rounded-apple-md transition-colors disabled:opacity-50"
            >
              {isExporting ? 'Exporting...' : 'Export All'}
            </button>
          </div>
        </div>
      </div>

      {/* Import Section */}
      <div className="space-y-4">
        <h3 className="text-lg font-medium text-ios-gray-900 dark:text-white">
          Import Data
        </h3>
        <p className="text-sm text-ios-gray-600 dark:text-ios-gray-400">
          Import data from a previously exported JSON file
        </p>
        
        <div className="p-4 bg-ios-gray-50 dark:bg-ios-gray-700 rounded-apple-lg">
          <div className="space-y-4">
            <input
              type="file"
              accept=".json"
              onChange={(e) => setImportFile(e.target.files?.[0] || null)}
              className="w-full px-3 py-2 bg-white dark:bg-ios-gray-600 border border-ios-gray-200 dark:border-ios-gray-500 rounded-apple-md text-ios-gray-900 dark:text-white file:mr-4 file:py-1 file:px-2 file:rounded-apple-sm file:border-0 file:bg-ios-blue file:text-white file:cursor-pointer"
            />
            {importFile && (
              <div className="flex items-center justify-between">
                <span className="text-sm text-ios-gray-600 dark:text-ios-gray-400">
                  Selected: {importFile.name}
                </span>
                <button
                  onClick={handleImport}
                  disabled={isImporting}
                  className="px-4 py-2 bg-ios-blue text-white rounded-apple-md hover:bg-ios-blue/90 transition-colors disabled:opacity-50"
                >
                  {isImporting ? 'Importing...' : 'Import'}
                </button>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Danger Zone */}
      <div className="space-y-4 pt-6 border-t border-ios-gray-200 dark:border-ios-gray-700">
        <h3 className="text-lg font-medium text-ios-red">
          Danger Zone
        </h3>
        <p className="text-sm text-ios-gray-600 dark:text-ios-gray-400">
          These actions cannot be undone. Please be careful.
        </p>
        
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <button
            onClick={() => handleClearData('articles')}
            className="px-4 py-2 bg-ios-red/10 hover:bg-ios-red/20 text-ios-red border border-ios-red/20 rounded-apple-md transition-colors"
          >
            Clear Articles
          </button>
          <button
            onClick={() => handleClearData('settings')}
            className="px-4 py-2 bg-ios-red/10 hover:bg-ios-red/20 text-ios-red border border-ios-red/20 rounded-apple-md transition-colors"
          >
            Reset Settings
          </button>
          <button
            onClick={() => handleClearData('all')}
            className="px-4 py-2 bg-ios-red hover:bg-ios-red/90 text-white rounded-apple-md transition-colors"
          >
            Clear All Data
          </button>
        </div>
      </div>
    </div>
  );
};

export default DataManager;